export const checkType = data => {
    let t = Object.prototype.toString.call(data).slice(8, -1)
    return t
}

// 深层拷贝
export const deepClone = target => {
    let targetType = checkType(target)
    let result
    if (targetType === "Object") {
        result = {}
    } else if (targetType === "Array") {
        result = []
    } else {
        return target
    }
    for (let i in target) {
        let value = target[i] // 每个属性对应的值
        // 兼容引用数据类型中还存在引用数据类型的情况
        let valueType = checkType(value)
        if (valueType === "Object" || valueType === "Array") {
            result[i] = deepClone(value) // 递归
        } else {
            result[i] = value
        }
    }
    return result
}

// 返回 09 10 ...
export const returnStr = str => {
    return (+str) > 9 ? str : `0${str}`;
}

/**
 * 转换时间 timer 时间戳, join 分隔符 默认- showTime 是否显示时分秒
 * @param {*} timer  时间戳
 * @param {*} join 分隔符 年月日的
 * @param {*} showTime 是否显示时分秒
 * @param {*} timeFiled 时分秒格式 hms 都显示 hm 只显示时分
 * @returns 
 */
export const transformDate = (timer, join="-", showTime=true, timeFiled='hms', hJoin = ":") => {
    if(!timer) {
        return 
    }
    if(timer.length < 11) {
        timer = +timer * 1000;
    }
    let date = new Date(+timer);
    let y = date.getFullYear();
    let m = date.getMonth() + 1;
    let d = date.getDate();
    let h = date.getHours();
    let f = date.getMinutes();
    let s = date.getSeconds(); 
    let str = ''
    str = `${y}${join}${returnStr(m)}${join}${returnStr(d)}`;
    if(showTime) {
        if(timeFiled === 'hms') {
            str = str + ` ${returnStr(h)}${hJoin}${returnStr(f)}${hJoin}${returnStr(s)}`;
        } else if(timeFiled === 'hm') {
            str = str + ` ${returnStr(h)}${hJoin}${returnStr(f)}`;
        }
    }
    return str;
}
/**
 * 根据天数返回最近几天开始日期和结束日期
 * @param {numer} day //最近几天 比如2 最近2天
 */
export const getBeginEndDate = (day) => {
    let myDate = new Date();
    myDate.setDate(myDate.getDate() - day);
    return [myDate, new Date()]
}

//get请求连接参数
export const genParams = ( data ) => {
    var params = ''
    for(let key in data) {
        params += key + "=" + data[key] + '&'
    }
    
    params = "?" +  params.substring(0, params.length-1);
    return params;
}
// 获取本地localStorage值
export const getLoaclData = (key) => {
    return window.localStorage.getItem(key);
}
// 保存本都localStorage值
export const saveLocalData = (key, value) => {
    if(checkType(value) === 'object' || checkType(value) === 'array') {
        value = JSON.stringify(value)
    }
    window.localStorage.setItem(key, value);
}

export const clearLocalData = (key) => {
    window.localStorage.removeItem(key)
}

// 比较两个日期
export const compareDate = (begin_time, end_time) => {
    if(begin_time && !end_time) {
        return false
    }
    if(begin_time && end_time) {
        if(new Date(begin_time).getTime() > new Date(end_time).getTime()) {
            //  结束时间比开始时间小
            return true;
        }
    }
    return false
}

// loading
export const showLoading = (msg="努力加载中...") => {
	let div = document.createElement('div');
	div.className = 'yx-loading';
	div.id = 'loading';
	div.innerHTML = `<div class='loadDiv'></div><p class='loadcont'>${msg}</p>`;
	document.body.appendChild(div)
}

export const hideLoading = () => {
	let loadingDiv = document.getElementById('loading');
	loadingDiv&&document.body.removeChild(loadingDiv)
}

export const appSource = () => {
	const u = navigator.userAgent;
	const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) || (u.indexOf('iOS') > -1);
	if (isiOS) {
		return "ios";
	} else {
		return "android";
	}
}

export const toUTCDate = (dateObj) => {
    if(!dateObj) {
        dateObj = new Date();
    }
    // 使用 getUTC* 方法来获取UTC时间的各个部分  
    let utcYear = dateObj.getUTCFullYear();  
    let utcMonth = String(dateObj.getUTCMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1  
    let utcDate = String(dateObj.getUTCDate()).padStart(2, '0'); 
    let utcTimeString = `${utcYear}-${utcMonth}-${utcDate}`;  

    console.log('toUTCDate', utcMonth, dateObj)
  
    return utcTimeString
}


// 获取UTC
export const getOffsetUtcDate = (dateObj, offset = 7) => {
    let firstDate = '';
    if (!dateObj) {
        dateObj = new Date();
        firstDate = new Date();
    } else {
        firstDate = new Date(dateObj);
    }
   
    firstDate = firstDate.setDate(firstDate.getDate() - offset)

    let start_date = toUTCDate(new Date(firstDate));
    let end_date = toUTCDate(new Date(dateObj));

    if(offset < 0) {
        return [end_date, start_date]
    }

    return [start_date, end_date];
}

//获取秒数转为 05:00
export const formatSeconds = (seconds) => {  
    var minutes = Math.floor(seconds / 60);  
    var remainingSeconds = seconds % 60;  
  
    // 确保分钟和秒都是两位数  
    minutes = minutes < 10 ? '0' + minutes : minutes;  
    remainingSeconds = remainingSeconds < 10 ? '0' + remainingSeconds : remainingSeconds;  
  
    return minutes + ':' + remainingSeconds;  
} 

export const setLocalStorage = (name, data) => {
    if (typeof data === 'object') {
        data = JSON.stringify(data)
    }
    localStorage.setItem(name, data)
}

export const getLocalStorage = (name, defaultVal = null) => {
    let data = localStorage.getItem(name);
    if (data && typeof data === "string") {
        try {
            data = JSON.parse(data)
        } catch (e) {
            data = data || defaultVal;
        }
    }
    if ((data == '' || data == undefined || data == 'undefined') && defaultVal != null) {
        return defaultVal
    }
    return data
}

export const removeLocalStorage = (name) => {
    if(!name) return;
    localStorage.removeItem(name)
}